<template>
  <zcb-dialog
    v-if="config.showAddressDrawer"
    v-model="config.showAddressDrawer"
    :title="config.drawerInfo.title"
    @click.stop
    width="500px"
    :show-close="false"
  >
    <zcb-form ref="formRef" v-model="formData" :options="{ span: 24 }" :schema="formListModel">
      <template #addressCode="{ item }">
        <el-select
          v-model="codes[0]"
          clearable
          :style="{
            width:
              'calc(100% / ' + item.displayFormat === 'TOW_LEVEL'
                ? 2
                : item.displayFormat === 'THREE_LEVEL'
                ? 3
                : item.displayFormat === 'FOUR_LEVEL'
                ? 4
                : 4 + ')'
          }"
          :placeholder="t('keys.pleaseSelect')"
          @change="(val) => valueChange(val, 0, item)"
        >
          <el-option v-for="item in ONELEVEL" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-select
          v-model="codes[1]"
          clearable
          :style="{
            width:
              'calc(100% / ' + item.displayFormat === 'TOW_LEVEL'
                ? 2
                : item.displayFormat === 'THREE_LEVEL'
                ? 3
                : item.displayFormat === 'FOUR_LEVEL'
                ? 4
                : 4 + ')'
          }"
          v-if="['TOW_LEVEL', 'THREE_LEVEL', 'FOUR_LEVEL'].includes(item.displayFormat)"
          :placeholder="t('keys.pleaseSelect')"
          @change="(val) => valueChange(val, 1, item)"
        >
          <el-option v-for="item in TOWLEVEL" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-select
          v-model="codes[2]"
          clearable
          :style="{
            width:
              'calc(100% / ' + item.displayFormat === 'TOW_LEVEL'
                ? 2
                : item.displayFormat === 'THREE_LEVEL'
                ? 3
                : item.displayFormat === 'FOUR_LEVEL'
                ? 4
                : 4 + ')'
          }"
          v-if="['THREE_LEVEL', 'FOUR_LEVEL'].includes(item.displayFormat)"
          :placeholder="t('keys.pleaseSelect')"
          @change="(val) => valueChange(val, 2, item)"
        >
          <el-option v-for="item in THREELEVEL" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-select
          v-model="codes[3]"
          clearable
          :style="{
            width:
              'calc(100% / ' + item.displayFormat === 'TOW_LEVEL'
                ? 2
                : item.displayFormat === 'THREE_LEVEL'
                ? 3
                : item.displayFormat === 'FOUR_LEVEL'
                ? 4
                : 4 + ')'
          }"
          v-if="['FOUR_LEVEL'].includes(item.displayFormat)"
          :placeholder="t('keys.pleaseSelect')"
          @change="(val) => valueChange(val, 3, item)"
        >
          <el-option v-for="item in FOURLEVEL" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </template>
      <template #defultReceiveFlag>
        <div style="width:100%">
          <div>
            <el-checkbox v-model="formData.receiveFlag" @change="!formData.receiveFlag ? (formData.defultReceiveFlag = false) : false"
              >收货地址</el-checkbox
            >
            <el-checkbox v-if="formData.receiveFlag" v-model="formData.defultReceiveFlag">默认收货地址</el-checkbox>
          </div>
          <div>
            <el-checkbox v-model="formData.invoiceFlag" @change="!formData.invoiceFlag ? (formData.defultInvoiceFlag = false) : false"
              >收票地址</el-checkbox
            >
            <el-checkbox v-if="formData.invoiceFlag" v-model="formData.defultInvoiceFlag">默认收票地址</el-checkbox>
          </div>
        </div>
      </template>
    </zcb-form>
    <template #btns>
      <el-button type="info" @click.stop="cancelClick">关闭</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </zcb-dialog>
</template>

<script setup>
import { ref, watch, reactive, toRaw, nextTick, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { validMobile, valilinteger } from 'utils/validate.js'
import { getLovValueInfoApi, postAddressApi, putAddressApi, getProvinceApi, getAreaApi } from 'api/home'
import { ERR_OK } from 'config/statusCode'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文

import { useMock } from '../hooks/mock.js'
const { formList } = useMock()
const formListModel = ref(formList)
const config = defineProps({
  showAddressDrawer: {
    type: Boolean,
    default: false
  },
  drawerInfo: {
    type: Object,
    default: {}
  }
})
const emits = defineEmits(['sonBtnCloseClick'])
const btnLoading = ref(false)
const formData = ref({
  contactsName: '',
  phone: '',
  landlinePhone: '',
  zipCode: '',
  provinceCode: '',
  cityCode: '',
  areaCode: '',
  addressCode: '',
  addressName: '',
  countryCode: 'CHN',
  countryName: '中国',
  countryCodeCn: '中国',
  street: '',
  defultReceiveFlag: true,
  defultInvoiceFlag: true,
  receiveFlag: true,
  invoiceFlag: true
})
const codes = ref(['', '', '', ''])
const names = ref(['', '', '', ''])
const ONELEVEL = ref([])
const TOWLEVEL = ref([])
const THREELEVEL = ref([])
const FOURLEVEL = ref([])
const formRef = ref(null)
const valueChange = (value, level, item) => {
  let res = {}
  switch (level) {
    case 0:
      codes.value = ['', '', '', '']
      names.value = ['', '', '', '']
      res = ONELEVEL.value.find((v) => v.code === value)
      names.value[level] = res.name
      getArea(value, level)
      break
    case 1:
      res = TOWLEVEL.value.find((v) => v.code === value)
      names.value[level] = res.name
      getArea(value, level)
      break
    case 2:
      res = THREELEVEL.value.find((v) => v.code === value)
      names.value[level] = res.name
      getArea(value, level)
      break
    case 3:
      res = FOURLEVEL.value.find((v) => v.code === value)
      names.value[level] = res.name
      formData.value['addressCode'] = JSON.stringify(codes.value)
      formData.value['addressName'] = names.value.join(' ')
      break
    default:
      break
  }
  codes.value[level] = value
}
// 获取下拉框的选择项数据
const getProvince = async () => {
  const { code, data } = await getProvinceApi()
  if (code === ERR_OK) {
    ONELEVEL.value = data.list
  }
}
const getArea = async (val, level) => {
  let Params = {
    areaCode: val
  }
  // 下拉框公共接口
  const { code, data } = await getAreaApi(Params)
  if (code === ERR_OK) {
    level === 0 ? (TOWLEVEL.value = data.list) : level === 1 ? (THREELEVEL.value = data.list) : (FOURLEVEL.value = data.list)
  }
}

const cancelClick = () => {
  formRef.value.resetForm()
  formRef.value.clearFormValidate()
  emits('sonBtnCloseClick', false)
  btnLoading.value = false
}
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      postAddress()
    } else {
      btnLoading.value = false
    }
  })
}
const postAddress = async () => {
  const params = { ...formData.value }
  let api = config.drawerInfo.type === 'edit' ? putAddressApi : postAddressApi
  const { code } = await api(params)
  if (code === ERR_OK) {
    btnLoading.value = false
    ElMessage({
      type: 'success',
      message: config.drawerInfo.type === 'edit' ? t('keys.edit_succeeded') : t('keys.Successfully_added')
    })
    cancelClick()
  }
  btnLoading.value = false
}
watch(
  () => config.showAddressDrawer,
  (newValue, oldValue) => {
    getProvince()
    if (newValue) {
      if (config.drawerInfo.type === 'edit') {
        let str = toRaw(config.drawerInfo.row)
        formData.value = {
          ...str,
          receiveFlag: str.defultReceiveFlag ? true : false,
          invoiceFlag: str.defultInvoiceFlag ? true : false
        }
        codes.value = JSON.parse(str.addressCode)
        names.value = str.addressName
        getArea(codes.value[0], 0)
        getArea(codes.value[1], 1)
        getArea(codes.value[2], 2)
      } else {
      }
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.htitle {
  font-size: 16px;
  font-weight: 550;
  color: #333333;
}
</style>
